package com.oscar.ehome.view.setview;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.oscar.ehome.R;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.setbean.AlipayBean;
import com.oscar.ehome.bean.setbean.PaySuccessBean;
import com.oscar.ehome.bean.setbean.WeChatBean;
import com.oscar.ehome.presenter.SetPresenter;
import com.oscar.ehome.provider.Aplay.PayResult;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.ButtonUtils;
import com.oscar.ehome.utils.util.Constants;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.setview.view.PayView;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PayActivity extends BasesActivity<PayView, SetPresenter> implements PayView {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 价格
     */
    @BindView(R.id.tv_price)
    TextView tvPrice;
    /**
     * 说明
     */
    @BindView(R.id.desc_text)
    TextView descText;
    /**
     * 微信选择
     */
    @BindView(R.id.rb_wx)
    Button rbWx;
    /**
     * 支付宝选择
     */
    @BindView(R.id.rb_zfb)
    Button rbZfb;
    /**
     * 支付
     */
    @BindView(R.id.confirm_pay)
    Button confirmPay;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    /**
     * 折扣
     */
    @BindView(R.id.paydiscount_text)
    TextView paydiscountText;

    String payway = "";
    String discount = "";


    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;

    private static final int SDK_PAY_FLAG = 1;

    SetPresenter setPresenter;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(PayActivity.this, PaysuccesActivity.class));
                        finish();

                    } else {
                        confirmPay.setFocusable(true);
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        ButterKnife.bind(this);
        setColor();
        initView();
    }

    @Override
    protected SetPresenter createPresenter() {
        setPresenter = new SetPresenter(this);
        return setPresenter;
    }


    /**
     * 设置颜色
     */
    public void setColor() {
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(PayActivity.this).getSystemConfig().getColor()));
        TintManager.setTint(confirmPay, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(rbWx, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(rbZfb, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }

    /**
     * 初始数据
     */
    public void initView() {

        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleImgBack.setVisibility(View.VISIBLE);
        titleTopbar.setText("支付");
        payway = "微信支付";

        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(PayActivity.this, Constants.APP_ID, false);

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        String price = bundle.getString("price");
        String payDesc = bundle.getString("payDesc");
        discount = bundle.getString("discount");

        if (price == null || "".equals(price)) {
            tvPrice.setText("暂无");
        } else {
            tvPrice.setText(price + "元");
        }

        descText.setText(payDesc);
        if (!"0".equals(discount)) {
            paydiscountText.setVisibility(View.VISIBLE);
            paydiscountText.setText(discount);
        }
    }

    //微信支付
    //  wxpay(prepayId, sign, appId, partnerId,nonceStr,packageStr,timeStamp);
    private void wxpay(String prepayId, String sign, String appId, String partnerId, String nonceStr, String packageStr, String timeStamp) {
        api.registerApp(appId);

        Toast.makeText(PayActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
        try {

            PayReq req = new PayReq();
            req.appId = appId;//应用ID
            req.partnerId = partnerId;//商户号ID”
            req.prepayId = prepayId;//重要，预支付交易会话ID“，
            req.nonceStr = nonceStr;//随机数
            req.timeStamp = timeStamp;//unixtime,时间戳
            req.packageValue = packageStr;// ”,
            req.sign = sign;// Sign=WXPay”,
            //  req.extData = "app data"; // optional/订单号,用此值去查询订单状态,这个值调用微信支付掊口时，不要传入”
            //Toast.makeText(PayActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            // 将该app注册到微信

            if (api.sendReq(req)) {

                finish();
            } else {
                Toast.makeText(PayActivity.this, "生成订单失败，请稍后重试", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //支付宝支付
    private void Alipay(String aliAppPayStr) {

        final String orderInfo = aliAppPayStr;   // 订单信息

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void getWeChat(WeChatBean weChatBean) {

        //预支付交易会话ID
        String prepayId = weChatBean.getPrepayId();
        //签名
        String sign = weChatBean.getSign();
        //应用ID
        String appId = weChatBean.getAppId();
        //商户号
        String partnerId = weChatBean.getPartnerId();
        //随机数
        String nonceStr = weChatBean.getNonceStr();
        //包
        String packageStr = weChatBean.getPackageStr();
        //时间戳
        String timeStamp = weChatBean.getTimeStamp();

        wxpay(prepayId, sign, appId, partnerId, nonceStr, packageStr, timeStamp);
    }

    @Override
    public void getAlipay(AlipayBean alipayBean) {

        String aliAppPayStr = alipayBean.getAliAppPayStr();
        String orderNo = alipayBean.getOrderNo();
        String payDescription = alipayBean.getPayDescription();
        double price = alipayBean.getPrice();
        Alipay(aliAppPayStr);


    }

    @Override
    public void getUserPayInfo(PaySuccessBean paySuccessBean) {

    }

    @Override
    public void erroy() {
        confirmPay.setFocusable(true);
        ToastUtil.show(PayActivity.this, getString(R.string.erry));
    }

    @Override
    public void erry(String result) {
        confirmPay.setFocusable(true);
        Toast.makeText(PayActivity.this, result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(PayActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(PayActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 支付
     */
    public void PayDesc() {
        if (!ButtonUtils.isFastDoubleClick()) {
            if (payway.equals("微信支付")) {
                ///检查微信版 本是否支持支付
                boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
                if (isPaySupported) {
                    setPresenter.getWeChat(SystemConfigFactory.getInstance(PayActivity.this).getSystemConfig().getToken());
                } else {
                    Toast.makeText(PayActivity.this, "请下载最新版本的微信完成支付", Toast.LENGTH_SHORT).show();
                }

            } else if (payway.equals("支付宝支付")) {
                //支付宝支付
                setPresenter.getAlipay(SystemConfigFactory.getInstance(PayActivity.this).getSystemConfig().getToken());

            } else {
                Toast.makeText(PayActivity.this, "请先选择支付方式", Toast.LENGTH_SHORT).show();
            }

        }
    }


    @OnClick({R.id.title_layout_left, R.id.liear_wx, R.id.liear_zfb, R.id.confirm_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_layout_left://返回
                finish();
                break;
            case R.id.liear_wx://微信
                payway = "微信支付";
                rbWx.setBackgroundResource(R.mipmap.danxuanzhong);
                rbZfb.setBackgroundResource(R.mipmap.danxuan);
                break;
            case R.id.liear_zfb://支付宝
                payway = "支付宝支付";
                rbWx.setBackgroundResource(R.mipmap.danxuan);
                rbZfb.setBackgroundResource(R.mipmap.danxuanzhong);
                break;
            case R.id.confirm_pay://支付
                confirmPay.setFocusable(false);
                PayDesc();
                break;
        }
    }


}
